package com.youhome.controller;

import cn.jsms.api.JSMSClient;
import cn.jsms.api.SendSMSResult;
import cn.jsms.api.common.model.SMSPayload;

import com.youhome.config.SMSConfig;
import com.youhome.response.Result;
import com.youhome.response.ResultCode;
import com.youhome.service.UserService;
import com.youhome.utils.ValidationUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * Created by chen365 on 2017/7/17.
 */
@Api(tags = "短信")
@RestController
@RequestMapping(value = "/sms")
public class SMSController {

    @Autowired
    private SMSConfig smsConfig;

    @Autowired
    private UserService userService;

    /**
     * 获取验证短信
     *
     * @param phone 手机号
     * @return
     */
    @ApiOperation(value = "获取短信验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "phone", value = "手机号码", required = true, paramType = "path")
    })
    @GetMapping(value = "/{phone}")
    public Object sms(@PathVariable String phone) {
        try {
            if (!ValidationUtils.isPhone(phone)) {
                return new Result(ResultCode.PHONE_ERROR);
            }

            if (userService.selectByPhone(phone) == null) {
                return new Result(ResultCode.PHONE_NOT_REGISTERED);
            }

            JSMSClient jsmsClient = new JSMSClient(smsConfig.getSecret(), smsConfig.getAppkey());
            SMSPayload payload = SMSPayload.newBuilder().setMobileNumber(phone).setTTL(300).setTempId(107224).build();

            SendSMSResult result = jsmsClient.sendSMSCode(payload);
            if (result.isResultOK()) {
                return new Result(ResultCode.SUCCESS, result.getMessageId().toString());
            } else {
                return new Result(ResultCode.FAIL, result.getOriginalContent());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(ResultCode.FAIL);
    }
}
